<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content compus">
      <el-row>
        <el-col :span="12">
          <e-heading style="margin-top:0;" :grade="'1'">
            {{this.$route.path.indexOf('add') == -1 ? '编辑校区': '新增校区'}}
          </e-heading>
        </el-col>
      </el-row>
  
        
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item
          prop="schoolName"
          label="校   区："
          :rules="[
              { required: true, message: '请输入校区名称'},
              { validator: schoolNameExist, message: '校区名称已存在', trigger: 'blur'}
          ]">
          <el-input class="fl add-input" v-model.trim="form.schoolName" :maxlength="50"  placeholder="请输入校区名称" style="90%"></el-input>
        </el-form-item>

        <el-form-item label="负责人：">
          <el-input class="fl add-input" v-model.trim="form.manager" :maxlength="20" placeholder="请输入负责人名称"></el-input>
        </el-form-item>
        <el-form-item label="电 话：" 
          prop="managerPhone"
          :rules="[
            form.managerPhone ? validator.rule.isPhoneAndLandline : ''
          ]">
          <el-input class="fl add-input" v-model.trim="form.managerPhone" placeholder="请输入负责人电话"></el-input>
        </el-form-item>
        <el-form-item label="地图坐标：">
          <Map @mapUpdata="getMapData" :mapAddress="mapAddress" :longitude="form.longitude" :latitude="form.latitude"></Map>
        </el-form-item>

        <el-form-item 
          prop="address"
          label="详细地址："
          :rules="[{ required: true, message: '请选择省市区，输入详细地址'}]">
            <div style="text-align:left">
              <e-address-cascader style="margin-bottom: 15px;width: 85%;"
                v-if="!mapAddress"
                placeholder="请选择省市区"  
                v-model="form.area" :grade="3" 
                :label.sync="form.location">
              </e-address-cascader>
              <el-input class="fl add-input" v-model.trim="form.address" :maxlength="50" placeholder="请输入详细地址"></el-input>&nbsp;<el-button type="link" style="line-height:36px;" @click="handleResetAddress" v-if="mapAddress">修改地址</el-button>
            </div>
        </el-form-item>
        
        <el-form-item 
          prop="listTrainVenuesAddress"
          label="上课地点："
          :rules="[
              { required: true, message: '请输入上课地点'},
              Object.assign({}, validator.rule.venuesAddress,{message: '上课地点不能为空'})
          ]">
          <div v-for="(item,index) in form.listTrainVenuesAddress" :key="index" class="address-item" v-show="item.status == 1">
            <el-input  placeholder="请输入该校区的上课场地、场馆或教室名称" :maxlength="10" v-model.trim="item.address" :disabled="item.readonly" class="address-input" @blur="handleCheckRepetition(item.address)">
            </el-input>
            <template v-if="!item.readonly">
              <el-button icon="plus" class="btn-icon" v-if=" index == form.listTrainVenuesAddress.length -1 "
                @click="handlePlusAddress()" :disabled="index == maxAddressLength - 1"></el-button>
              <el-button icon="minus" class="btn-icon" v-else
                @click="handleMinusAddress(index)" ></el-button>
            </template>
            <template v-else >
              <el-button icon="plus" class="btn-icon" v-if=" index == form.listTrainVenuesAddress.length -1 || form.listTrainVenuesAddress.length<=1 "
                @click="handlePlusAddress()" :disabled="index == maxAddressLength - 1"></el-button>
            </template>    
          </div>
        </el-form-item>
        
        <el-form-item 
          prop="transitInfo"
          label="交通信息：">
          <el-row class="mb20">
            <el-col :span="2">
              <el-button>地铁</el-button>
            </el-col>
            <el-col :span="19">
              <el-input class="trafic-info" v-model.trim="form.metroInfo"></el-input>
            </el-col>
          </el-row>
          <el-row class="mb20">
            <el-col :span="2">
              <el-button>公交</el-button>
            </el-col>
            <el-col :span="19">
              <el-input class="trafic-info" v-model.trim="form.transitInfo"></el-input>
            </el-col>
          </el-row>
          <el-row class="mb20">
            <el-col :span="2">
              <el-button>停车</el-button>
            </el-col>
            <el-col :span="19">
              <el-input class="trafic-info" v-model.trim="form.parkInfo"></el-input>
            </el-col>
          </el-row>     
          <p class="small center" style="width:300px;">完善校区信息，有助于买家更了解学校信息哦！</p>     
        </el-form-item>
      </el-form>
      <div class=" center">
        <router-link :to="{
            path: '/training/campus'
          }">
          <el-button @click="">取 消</el-button>
        </router-link>
        <el-button type="primary" @click="handleSave">保 存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import Api from 'api/train'
import validator from 'utils/validator'
import EGroup from '@e-ui/Group'
import EAddressCascader from '@e-ui/AddressCascader'
import { mapGetters } from 'vuex'
import Map from './components/Map'
import VueAMap from 'vue-amap' // 引入高德地图
let amapManager = new VueAMap.AMapManager()
export default {
  components: {
    EAddressCascader,
    EGroup,
    Map
  },
  computed: {
    ...mapGetters({
      train_compus_selection: 'train_compus_selection' // 学员列表数据
    }),
    selectionOption () {
      let option = []
      for (let i = 0; i < this.train_compus_selection.length; i++) {
        option.push({
          label: this.train_compus_selection[i].provinceName + '-' + this.train_compus_selection[i].cityName,
          value: this.train_compus_selection[i].provinceId + '-' + this.train_compus_selection[i].cityId
        })
      }
      return option
    },
    initValue: {
      set (value) {
        value = value.split('-')
        this.query.provinceId = value[0] || null
        this.query.cityId = value[1] || null
      },
      get (value) {
        if (this.query.provinceId === null || this.query.cityId === null) {
          return ''
        }
        value = this.query.provinceId + '-' + this.query.cityId
        return value
      }
    }
  },
  mounted () {
    this.getProvinceAndCities()
    if (this.$route.query.id) {
      this.getInfo()
    }
  },
  data () {
    let schoolNameExist
    return {
      amapManager,
      // 这里通过高德 SDK 完成。
      geocoder: new AMap.Geocoder({ // eslint-disable-line
        radius: 1000,
        extensions: 'all'
      }),
      schoolNameExist,
      validator,
      isEdit: false,
      selectedList: [],
      mapAddress: '',
      schoolList: {},
      school: {},
      rules: {},
      maxAddressLength: 10,
      form: {
        schoolName: '',
        manager: '',
        managerPhone: '',
        address: '', // 详细地址
        metroInfo: '',
        transitInfo: '',
        parkInfo: '',
        longitude: 0,
        latitude: 0,
        status: 1,
        orgUserId: '',
        createdTime: new Date().getTime(),
        id: '',
        listTrainVenuesAddress: [{
          id: '',
          schoolId: '',
          address: '',
          status: 1
        }], // 上课地点
        modifyId: '',
        area: [],
        location: '',
        provinceId: '',
        cityId: '',
        areaId: ''
      },
      trainSchool: {},
      venuesAddresses: [],
      OldName: '',
      selectionValue: ''
    }
  },
  methods: {
    getInfo () {
      let schoolId = this.$route.query.id
      Api.schoolDetails({schoolId: schoolId}).then(result => {
        let {trainSchool, venuesAddresses} = result.data
        this.trainSchool = trainSchool
        this.venuesAddresses = venuesAddresses
        this.OldName = trainSchool.schoolName
        let self = this
        this.schoolNameExist = (rule, value, callback) => {
          if (self.OldName !== self.form.schoolName) {
            Api.schoolNameValid({schoolName: value}).then((res) => {
              if (res.data === true) { // 校区名可用
                callback()
              } else {
                callback(new Error('校区名称已存在'))
              }
            })
          } else {
            callback()
          }
        }
        let readOnlyList = []
        let addressList = venuesAddresses
        Api.editValidate({schoolId: schoolId}).then((res) => {
          readOnlyList = res.data
          if (trainSchool.longitude || trainSchool.latitude) {
            this.mapAddress = trainSchool.address
          }
          this.form = trainSchool
          this.form.area = []
          this.form.area.push(trainSchool.provinceId)
          this.form.area.push(trainSchool.cityId)
          this.form.area.push(trainSchool.areaId)
          for (let i = 0, len = readOnlyList.length; i < len; i++) {
            for (let j = 0, jlen = addressList.length; j < jlen; j++) {
              if (readOnlyList[i] === addressList[j].id) {
                addressList[j].readonly = true
              }
            }
          }
          this.form.listTrainVenuesAddress = []
          if (venuesAddresses.length) {
            venuesAddresses.forEach(item => {
              this.form.listTrainVenuesAddress.push(item)
            })
          } else {
            this.form.listTrainVenuesAddress.push({
              id: '',
              schoolId: schoolId,
              address: '',
              status: 1
            })
          }
        })
      })
    },
    handleSave () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let f = this.form
          Api.addSchool({
            id: f.id,
            schoolName: f.schoolName,
            manager: f.manager,
            managerPhone: f.managerPhone,
            address: f.address,
            transitInfo: f.transitInfo,
            metroInfo: f.metroInfo,
            parkInfo: f.parkInfo,
            longitude: f.longitude,
            latitude: f.latitude,
            status: f.status,
            orgUserId: f.orgUserId,
            listTrainVenuesAddress: f.listTrainVenuesAddress,
            provinceId: f.area[0],
            cityId: f.area[1],
            areaId: f.area[2] || 0
          }, this).then((res) => {
            this.$router.push({
              path: '/training/campus'
            })
          })
        } else {
          return false
        }
      })
    },
    handleAdd () {
      this.isEdit = false
      this.form = {
        id: '',
        schoolName: '',
        address: '',
        metroInfo: '',
        transitInfo: '',
        parkInfo: '',
        longitude: 0,
        latitude: 0,
        status: 1,
        orgUserId: '',
        createdTime: new Date().getTime(),
        listTrainVenuesAddress: [
          {
            id: '',
            schoolId: '',
            address: '',
            status: 1
          }
        ],
        area: [],
        location: '',
        provinceId: '',
        cityId: '',
        areaId: ''
      }
    },
    handleCheckRepetition (val) { // 校验上课地点不能重复
      let nullArray = []
      if (val && this.form.listTrainVenuesAddress && this.form.listTrainVenuesAddress.length > 0) {
        this.form.listTrainVenuesAddress.forEach((item, i) => {
          if (nullArray.includes(item.address)) {
            this.form.listTrainVenuesAddress[i].address = ''
            this.$message({
              message: '同一校区上课地点不能重复',
              type: 'error'
            })
          } else {
            nullArray.push(item.address)
          }
        })
      }
    },
    // 添加上课地点
    handlePlusAddress () {
      this.form.listTrainVenuesAddress.push({
        id: '',
        schoolId: this.form.id || '',
        address: '',
        status: 1
      })
      this.$forceUpdate()
    },
    // 删除上课地点
    handleMinusAddress (i) {
      this.form.listTrainVenuesAddress[i].status = 0
    },
    getProvinceAndCities () {
      this.$store.dispatch('train_compus_selection')
    },
    getMapData (mapData) { // 获取地图数据
      this.mapAddress = mapData.adress
      this.form.longitude = mapData.lng
      this.form.latitude = mapData.lat
      this.form.address = this.mapAddress
      this.form.area = [0, 0, 0]
    },
    handleResetAddress () { // 清除地图数据修改地址
      this.mapAddress = ''
      this.form.address = ''
      this.form.longitude = 0
      this.form.latitude = 0
    },
    getCityName (obj, lng, lat) {
      let scope = this
      if (lng && lat) {
        scope.geocoder.getAddress([lng, lat], function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              // 生成坐标地址
              obj.cityName = result.regeocode.addressComponent.city || result.regeocode.addressComponent.province
            }
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.campus-table{
  margin: 20px 0;
}
.center{
  text-align: center;
}
.no-data{
  padding-top: 50px;
  p{
    color: #333;
    margin: 20px 0 30px;
  }
}
.mb20{
  margin-bottom: 20px;
  margin-right:15px;
  .el-button{
    min-width:0;
    padding-left: 10px;
    padding-right: 10px;
  }
}
.add-input{
  width:85%;
}
.address-item{
  margin-bottom: 10px;
  text-align: left;
}
.address-input{
  width: 571px;
}
</style>
<style lang="scss">
.form-wrapper{
  max-height: 560px;
  overflow-y: scroll;
}
.campus-table tr td {
  font-size: 12px;
}
.compus .el-form-item__content > .el-select{
  width:auto
}
.compus_dialog{
  .el-dialog--small{
    width:750px;
  }
}
.trafic-info{
  width: 565px;
}
</style>
